package org.jeecg.modules.htxincailiao.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.tips.ErrorTip;
import org.jeecg.common.util.*;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.cart.service.IHTCartService;
import org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum;
import org.jeecg.modules.htxincailiao.order.constant.HTOrderTypeEnum;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTOrderInfoBO;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTSubmitOrderBO;
import org.jeecg.modules.htxincailiao.order.domain.dto.HTConfirmOrderDTO;
import org.jeecg.modules.htxincailiao.order.domain.dto.HTOrderQueryDTO;
import org.jeecg.modules.htxincailiao.order.domain.dto.HTSubmitOrderDTO;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderSalesStatisticsVO;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderStatisticsVO;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderVO;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTSubmitOrderVO;
import org.jeecg.modules.htxincailiao.order.entity.HTOrder;
import org.jeecg.modules.htxincailiao.order.service.IHTOrderService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum.CONFIRM_FROM_CART;
import static org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum.ORDERED;

/**
 * @Description: ht_order
 * @Author: jeecg-boot
 * @Date: 2021-11-08 16:58:42
 * @Version: V1.0
 */
@Api(tags = "ht_order")
@RestController
@RequestMapping("/order/hTOrder")
@Slf4j
public class HTOrderController extends JeecgController<HTOrder, IHTOrderService> {
    @Resource
    IHTCartService cartService;
    @Resource
    private IHTOrderService orderService;
    @Resource
    private IHTAccountService accountService;

    /**
     * @return 订单统计
     */
    @GetMapping(value = "getStatistics")
    public Result<JSONObject> getStatistics(HttpServletRequest request, String dayTime) {
        Result<JSONObject> result = new Result<>();
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isNotEmpty(token)) {
            if (oConvertUtils.isEmpty(dayTime)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dayTime = DateUtils.date2Str(dateFormat);
            }

            HTOrderStatisticsVO vo = orderService.getStatistics(dayTime);
            result.setResult(JSONObject.parseObject(JSONObject.toJSONString(vo)));
        } else {
            result.error500("请先登录");
        }

        return result;
    }

    /**
     * @return 销售统计
     */
    @GetMapping(value = "getSalesStatistics")
    public Result<JSONObject> getSalesStatistics(HttpServletRequest request, String beginTime, String endTime) throws ParseException {
        Result<JSONObject> result = new Result<>();
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);

        if (oConvertUtils.isNotEmpty(token)) {
            List<HTOrderSalesStatisticsVO> list = orderService.getSalesStatistics(beginTime, endTime);
            List<String> monthRange = DateTimeUtil.getMonthRange(beginTime, endTime);
            List<HTOrderSalesStatisticsVO> combineList = new ArrayList<>();
            for (String month : monthRange) {
                List<HTOrderSalesStatisticsVO> resultList =
                        list.stream().filter(vo-> oConvertUtils.isNotEmpty(vo.getMonthInterval()) && vo.getMonthInterval().equals(month)).collect(Collectors.toList());
                if(resultList.size() > 0){
                    HTOrderSalesStatisticsVO vo = resultList.get(0);
                    combineList.add(vo);
                }
                else {
                    HTOrderSalesStatisticsVO vo = new HTOrderSalesStatisticsVO();
                    vo.setMonthInterval(month);
                    combineList.add(vo);
                }

            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", combineList);
            result.setResult(jsonObject);
        } else {
            result.error500("请先登录");
        }

        return result;
    }


    /**
     * 导航加载购物车
     *
     * @param @param request
     * @return Result
     * @throws
     * @Title: cart
     * @Description: 订单列表 （按子订单整合）
     */
    @RequestMapping(value = "/parentList", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> groupedListByStore(HTOrder htOrder,
                                        HttpServletRequest req,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                htOrder = JSONObject.parseObject(line, HTOrder.class);
                pageNo = oConvertUtils.isNotEmpty(htOrder.getPageNo()) ? htOrder.getPageNo() : pageNo;
                pageSize = oConvertUtils.isNotEmpty(htOrder.getPageSize()) ? htOrder.getPageSize() : pageSize;
            }
        }

        Result<IPage<HTOrderVO>> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (oConvertUtils.isNotEmpty(user)) {
            htOrder.setBuyerId(user.getId());
            htOrder.setParentId("0");
        }

        QueryWrapper<HTOrder> queryWrapper = QueryGenerator.initQueryWrapper(htOrder, req.getParameterMap());

        Page<HTOrder> page = new Page<>(pageNo, pageSize);
        IPage<HTOrderVO> pageList = orderService.pageBy(page, queryWrapper);

        result.setResult(pageList);
        return result;
    }

    /**
     * 确认订单信息
     *
     * @Description:
     */
    @PostMapping(value = "/confirmOrderInfo")
    public Result<?> confirmOrderInfo(HttpServletRequest request, @RequestBody HTConfirmOrderDTO dto) throws Exception {
        Result<JSONObject> result = new Result();

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (oConvertUtils.isEmpty(user)) {
            result.error500("请先登录");
            return result;
        }

        HTOrderInfoBO bo = new HTOrderInfoBO();
        try {
            HTOrderInfoTypeEnum orderInfoType = dto.getOrderInfoType();
            bo.setOrderInfoType(orderInfoType);

            switch (orderInfoType) {
                case CONFIRM_FROM_GOODS: {
                    assert Objects.isNull(dto.getGoodsId()) : "立即购买GoodsID不能为空";
                    bo.setGoodsId(dto.getGoodsId());
                    bo.setQuantity(dto.getQuantity());
                }
                break;

                case CONFIRM_FROM_REPORT: {
                    assert Objects.isNull(dto.getReportId()) : "立即购买ReportID不能为空";
                    bo.setReportId(dto.getReportId());
                    bo.setQuantity(dto.getQuantity());
                }
                break;

                case CONFIRM_FROM_LIBRARY: {
                    assert Objects.isNull(dto.getLibraryId()) : "立即购买LibraryId不能为空";
                    bo.setLibraryId(dto.getLibraryId());
                    bo.setQuantity(dto.getQuantity());
                }
                break;

                case CONFIRM_FROM_CART: {
                    bo.setBuyerId(user.getId());
                }
                break;

                default:
                    break;
            }

            HTOrderVO orderInfo = orderService.getOrderInfoByOrderInfoType(bo);
            JSONObject obj = new JSONObject();
            obj.put("orderInfo", orderInfo);
            result.setResult(obj);

        } catch (Exception e) {
            e.printStackTrace();
            result.error500(ErrorTip.bzError);
        }

        return result;
    }

    /**
     * 订单信息
     *
     * @Description:
     */
    @PostMapping(value = "/info")
    public Result<?> info(HttpServletRequest request, @Valid @RequestBody HTOrderQueryDTO dto) throws Exception {
        Result<JSONObject> result = new Result();

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (user == null) {
            result.error500("请先登录");
        }

        HTOrderInfoBO bo = new HTOrderInfoBO();
        HTOrderVO orderInfo = null;
        try {
            bo.setOrderInfoType(ORDERED);
            bo.setOrderId(dto.getOrderId());
            orderInfo = orderService.getOrderInfoByOrderInfoType(bo);
            JSONObject obj = new JSONObject();
            obj.put("orderInfo", orderInfo);
            result.setResult(obj);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500(ErrorTip.bzError);
        }

        return result;
    }

    /**
     * 提交订单
     *
     * @Description:
     */
    @PostMapping(value = "submitOrder")
    public Result<?> submitOrder(HttpServletRequest request, @Valid @RequestBody HTSubmitOrderDTO dto) throws Exception {
        Result<JSONObject> result = new Result<>();
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        // 查询当前用户
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (oConvertUtils.isNotEmpty(user)) {
            HTSubmitOrderBO bo = SmartBeanUtil.copy(dto, HTSubmitOrderBO.class);
            bo.setBuyerId(user.getId());
            // 如果是购物车结算，需要去获取订单的商品类型
            if (dto.getOrderInfoType() == CONFIRM_FROM_CART) {
                HTOrderTypeEnum orderType = cartService.getOrderType();
                bo.setOrderType(orderType);
            }
            // 设置腾讯账号id
            if (oConvertUtils.isNotEmpty(user.getTencentAccountId())) {
                bo.setTencentAccountId(user.getTencentAccountId());
            }
            // 买家留言
            List<HashMap<String, String>> leaveMessages = null;
            if (oConvertUtils.isNotEmpty(dto.getLeaveMessageInfo())) {
                Class<HashMap<String, String>> clazz = (Class<HashMap<String, String>>) (Object) HashMap.class;
                leaveMessages = JSONObject.parseArray(dto.getLeaveMessageInfo(), clazz);
            }
            bo.setLeaveMessages(leaveMessages);
            // 接受资料邮箱
            bo.setReceivedArchivesEmail(dto.getReceivedArchivesEmail());
            // 保存订单
            HTSubmitOrderVO submitOrderVO = orderService.submitOrder(bo);
            // 组装返回数据
            JSONObject obj = new JSONObject();
            if (oConvertUtils.isNotEmpty(submitOrderVO.getPayment())) {
                obj.put("paymentInfo", submitOrderVO.getPayment());
            }
            obj.put("ordered", submitOrderVO.isOrdered());
            result.setResult(obj);
        } else {
            result.error500("请先登录");
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param hTOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_order-分页列表查询")
    @ApiOperation(value = "ht_order-分页列表查询", notes = "ht_order-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTOrder hTOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTOrder> queryWrapper = QueryGenerator.initQueryWrapper(hTOrder, req.getParameterMap());
        Page<HTOrder> page = new Page<>(pageNo, pageSize);
        IPage<HTOrder> pageList = orderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTOrder
     * @return
     */
    @AutoLog(value = "ht_order-添加")
    @ApiOperation(value = "ht_order-添加", notes = "ht_order-添加")
    @PostMapping(value = "/add")
    public Result<?> add(HttpServletRequest request, @RequestBody HTOrder hTOrder) {
        if (Objects.isNull(hTOrder.getBuyerId())) {
            String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
            String username = JwtUtil.getUsername(token);

            HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
            if (oConvertUtils.isNotEmpty(user)) {
                hTOrder.setBuyerId(user.getId());
            }
        }

        orderService.save(hTOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hTOrder
     * @return
     */
    @AutoLog(value = "ht_order-编辑")
    @ApiOperation(value = "ht_order-编辑", notes = "ht_order-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTOrder hTOrder) {
        orderService.updateById(hTOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_order-通过id删除")
    @ApiOperation(value = "ht_order-通过id删除", notes = "ht_order-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        orderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_order-批量删除")
    @ApiOperation(value = "ht_order-批量删除", notes = "ht_order-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.orderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_order-通过id查询")
    @ApiOperation(value = "ht_order-通过id查询", notes = "ht_order-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTOrder hTOrder = orderService.getById(id);
        if (hTOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTOrder hTOrder) {
        return super.exportXls(request, hTOrder, HTOrder.class, "ht_order");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTOrder.class);
    }

}
